
import express from 'express';
import Client from 'ssh2-sftp-client'
import multer from 'multer';
import {remoteSftpConfig} from  '../localConfig/config.js'

import  tableModule from '../models/index.js';
import {
    checkLogin,
} from './middleWare/index.js'


// 没有配置本地存储配置，使用临时存储
const upload = multer();
const router = express.Router()


const {
    appVersionModel
} = tableModule


// 查询app的历史版本信息
router.post("/getHistoryAppPackageInfoList",async(req,res)=>{
    const {fileOwnership} = req.body
    await appVersionModel.getHistoryAppPackageInfoList({fileOwnership}).then((data)=>{
        return res.json({
            code:200,
            message:'查询成功',
            data:data
        })
    })
})


// 获取最新版本的app信息
router.post("/getAppInfo",async(req,res)=>{
    const {fileOwnership} = req.body
    if(!fileOwnership){
        return res.status(500).json({
            code:500,
            message:'参数缺失',
            data:false
        })
    }

    let resGet = await appVersionModel.getAppPackageInfo({isAbandon:0,fileOwnership})
    
    const {version,filePath,fileName} = resGet || {}
    let resDate = {
        version,filePath,fileName
    }
    if(resGet){
        return res.json({
            code:200,
            message:'查询成功',
            data:resDate
        })
    }else{
        return res.status(500).json({
            code:500,
            message:'查询失败',
            data:null
        })
    }
})


//上传app
router.post("/uploadFile",upload.single('file'),checkLogin, async (req, res) => {
   const {version,fileOwnership} = req.body
   const file  = req.file
   if(!version || !fileOwnership){
    return res.status(500).json({
        code:500,
        message:'参数缺失',
        data:false
    })
   }
    if(!file?.originalname?.includes('.apk')){
        return res.status(500).json({
            code:500,
            message:'文件不合法',
            data:false
        })
    }
    let  remotePath = '/upload/' + fileOwnership + '_' + version+'.apk';   //服务器存放的地址 //sftp的相对路径
    // 上传文件到sftp服务
    let sftp = new Client();
    return sftp.connect(remoteSftpConfig).then(() => {
        // 上传文件
        return sftp.put(file.buffer, remotePath);
    }).then(async (data) => {
        sftp.end();
        // 同步文件信息到数据库（先更新旧数据的状态信息，再新增）
        let infoDate = {
            version:version,
            filePath:remotePath,
            fileName:`app_${fileOwnership}_${version}`,
            fileOwnership
        }
        let user = await appVersionModel.updateAppPackageInfo({isAbandon:0,fileOwnership},{isAbandon:1})
        if(!user){
            return res.status(500).json({
                code:500,
                message:'保存失败',
                data:false
            })
        }
        let addRes =  await appVersionModel.addAppPackageInfo(infoDate)
        if(addRes){
            return res.json({
                code:200,
                message:'保存成功',
                data:true
            })
        }else{
            return res.status(500).json({
                code:500,
                message:'保存失败',
                data:false
            })
        }
    }).catch((err) => {
        console.log('catch error', err);
        return res.status(500).json({
            code:500,
            message:'保存失败',
            data:false
        })
    });
})




//下载app
router.post("/downloadFile", async (req, res) => {
    //服务器文件存放的地址 //sftp的相对路径
    const {remotePath} = req.body
    if(!remotePath){
        return res.status(500).json({
            code:500,
            message:'传参缺失',
            data:false
        })
    }

    let sftp = new Client();
    await sftp.connect(remoteSftpConfig)

    // 先判断远程文件是否存在
    let isFileExit = await sftp.exists(remotePath)
    if(!isFileExit){
        sftp.end();
        return res.status(500).json({
            code:500,
            message:'文件不存在',
            data:null
        })
    }

    // 获取文件大小
    const stat = await sftp.stat(remotePath);
    const totalSize = stat.size;

    // 设置下载响应头
    res.setHeader('Content-Type', 'application/octet-stream');
    // res.setHeader('Content-Disposition', `attachment; filename="${remotePath.split('/').pop()}"`);
    res.setHeader('Content-Length', totalSize);
    await sftp.get(remotePath,res);

    sftp.end();   
})


// 删除app
router.post('/deleteFile',checkLogin,async (req,res)=>{
    const {id,remotePath} = req.body
    if(!id || !remotePath){
        return res.status(500).json({
            code:500,
            message:'传参缺失',
            data:null
        })
    }
    // 删除sftp服务中的对应文件信息
    let sftp = new Client();
    try{
        await sftp.connect(remoteSftpConfig)
        let isFileExit = await sftp.exists(remotePath)
        if(isFileExit){ await sftp.delete(remotePath) }
    }catch (err){
        console.error('删除失败',err.message);
        return res.status(500).json({
            code:500,
            message:'删除失败',
            data:false
        })
    }finally {
        sftp.end();
    }

    // 删除数据库记录
    let delRes =  await appVersionModel.deleteAppPackageInfo(id)
    if(delRes){
        return res.json({
            code:200,
            message:'删除成功',
            data:true
        })
    } else{
        return res.status(500).json({
            code:500,
            message:'删除失败',
            data:false
        })
    }
})


export default router;